package cn.huiyunche.driver.schedule;

import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.interfaces.impl.TmsOrderCallHistoryServiceImpl;
import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.vo.OrderConfirmResult;
import cn.huiyunche.base.service.vo.OrderDepartureVo;
import cn.huiyunche.driver.service.OrderService;
import cn.huiyunche.driver.service.TmsQueueDimensionService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * The type Tms order schedule.
 *
 * @FileName: cn.huiyunche.driver.schedule
 * @Description: 没10分钟抓取一次TMS订单数据
 * @author: Aaron
 * @date: 2016 /11/2 上午9:20
 */
//@Component
public class TMSOrderSchedule {

    private static final Logger logger = LoggerFactory.getLogger(TMSOrderSchedule.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private TmsQueueDimensionService tmsQueueDimensionService = null;
    
    /*@Autowired
    private TmsQueueService tmsQueueService = null;*/

    @Autowired
    private TmsOrderCallHistoryServiceImpl tmsOrderCallHistoryService;

    /**
     * 每5分钟抓取一次中联TMS系统订单
     * Import orders.
     */
    // @Scheduled(cron="0 0/5 * * * *")
    public void importOrders() {
        logger.info("jbo start: import orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
        final String url = TmsUrlConstant.PULL_IMPORT;

        //查询上一次成功url调用成功的记录
        Date lastTime = tmsOrderCallHistoryService.getLastTimeSuccess(TmsUrlTypeEnum.PULL_IMPORT.getValue(), true);

        Map<String, Object> paramsMap = new HashedMap<>();
        paramsMap.put("lastTime", new DateTime(lastTime).toString("yyyy-MM-dd HH:mm:ss:SSS"));

        String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_IMPORT.getValue(), paramsMap, 30000);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                List<TmsOrder> tmsOrders = JSONArray.parseArray(data, TmsOrder.class);
                logger.info("saveTmsOrders tmsOrders : {}", tmsOrders);
                orderService.handleTmsOrders(tmsOrders);
            }
        }

        /*List<TmsOrder> tmsOrders = this.tmsImportService.importOrderExcel();
        LOGGER.info("saveTmsOrders tmsOrders : {}", tmsOrders);
		if (CollectionUtils.isNotEmpty(tmsOrders)) {
			tmsOrderService.saveTmsOrders(tmsOrders);
		}*/
        logger.info("jbo end: import orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
    }

    /**
     * 每30分钟从中联TMS系统拉取确认后的回单
     * Import orders confirm.
     */
//    @Scheduled(cron="0 0/5 * * * *")
    public void importOrdersConfirm() {
        logger.info("jbo start: confirm orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
        final String url = TmsUrlConstant.PULL_ORDER_CONFIRM;

        //查询上一次成功url调用成功的记录
        Date lastTime = tmsOrderCallHistoryService.getLastTimeSuccess(TmsUrlTypeEnum.PULL_ORDER_CONFIRM.getValue(), true);

        Map<String, Object> paramsMap = new HashedMap<>();
        paramsMap.put("lastTime", new DateTime(lastTime).toString("yyyy-MM-dd HH:mm:ss:SSS"));

        String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_CONFIRM.getValue(), paramsMap, 30000);
        logger.info("zl confirm order finish job result : {}.", result);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                List<OrderConfirmResult> confirmResults = JSONArray.parseArray(data, OrderConfirmResult.class);
                if (CollectionUtils.isNotEmpty(confirmResults)) {
                    orderService.confirmResults(confirmResults);
                }
            }
        }
        logger.info("jbo end: confirm orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
    }

    /**
     * 确认发车
     */
    // @Scheduled(cron="0 0/5 * * * *")
    public void departureOrder() {
            /*	String data = "[{ \"dtshipdate\" : \"2016-11-17 13:36:41\", \"iorderid\" : 1402224, \"ordercost\" : { \"'firstfueltotal'\" : \"60\", \"'fuelstandard'\" : \"10\", \"'kilometer'\" : \"1000\", \"'km'\" : \"1200\", \"'marketprice'\" : \"6\", \"'oilapprice'\" : \"5\", \"'oilarprice'\" : \"5.5\", \"'oilpercent'\" : \"0.9000\", \"'price'\" : \"1.5\", \"'tankvolume'\" : \"60\" }, \"vccard\" : \"360426196505060055\", \"vcdriverno\" : \"CHNL3306\", \"vcorderno\" : \"0171066124\" }]";
        if(StringUtils.isNotBlank(data)){
            List<OrderDepartureVo> departureResults = JSONArray.parseArray(data, OrderDepartureVo.class);
            if(CollectionUtils.isNotEmpty(departureResults)){
                this.tmsOrderService.orderDeparture(departureResults);
            }
        }*/
        logger.info("jbo start: departure orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
        final String url = TmsUrlConstant.PULL_ORDER_DEPARTURE;
        //查询上一次成功url调用成功的记录
        Date lastTime = this.tmsOrderCallHistoryService.getLastTimeSuccess(TmsUrlTypeEnum.PULL_ORDER_DEPARTURE.getValue(), true);
        Map<String, Object> paramsMap = new HashedMap<>();
        paramsMap.put("lastTime", new DateTime(lastTime).toString("yyyy-MM-dd HH:mm:ss:SSS"));
        String result = this.tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_DEPARTURE.getValue(), paramsMap, 30000);
        logger.info("zl departure order finish job result : {}.", result);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                List<OrderDepartureVo> departureResults = JSONArray.parseArray(data, OrderDepartureVo.class);
                if (CollectionUtils.isNotEmpty(departureResults)) {
                    try {
                        orderService.orderDeparture(departureResults);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        logger.info("jbo end: departure orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
    }

    /**
     * 每1分钟派单一次
     * 派单操作
     */
    // @Scheduled(cron="0 0/1 * * * *")
    public void dispatchOrder() {
        logger.info("jbo start: dispatch orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
        // this.tmsQueueService.start();
        this.tmsQueueDimensionService.startDispatch();
        logger.info("jbo end: dispatch orders job time: {}", new DateTime().toString("yyyy-MM-dd HH:mm:ss:SSS"));
    }
}
